<template>
  <div class="medical-create-page">
    <div class="nav-bar" style="background: #FFFFFF">
      <div class="nav-status" :style="{height:statusH + 'px'}"></div>
      <div class="nav-head flex-center" :style="{height:titleH + 'px'}">
        <div class="flex-1 flex-row-v-center" style="padding-left: 10px;">
          <img style="width: 22px;height: 22px" src="/static/assets/img/icon/icon-arrow-left.png"
               @click="onClickGoBack()"/>
        </div>
        <div class="flex-1 flex-center">
          <span style="font-size: 18px; color:#000000">病历信息</span>
        </div>
        <div class="flex-1"></div>
      </div>
    </div>
    <div class="medical-create-container" :style="{'padding-top':titleH + statusH + 'px'}">
      <div class="line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">姓名</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <input class="item-value" placeholder="请输入姓名" v-model="name"/>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">{{name ? name : '暂无设置'}}</span>
        </div>
      </div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">微信号</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <input class="item-value" placeholder="请输入微信号" v-model="wxAccount"/>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">{{wxAccount ? wxAccount : '暂无设置'}}</span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">年龄</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <picker @change="bindPickerChange('age', $event)" :value="age" :range="ageArray">
            <view class="item-value">
              {{ageIndex ? ageArray[ageIndex] : '请选择'}}
            </view>
          </picker>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
            {{ageIndex ? ageArray[ageIndex] : '暂无设置'}}
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">性别</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <picker @change="bindPickerChange('sex', $event)" :value="gender" :range="sexArray">
            <view class="item-value">
              {{sexIndex ? sexArray[sexIndex] : '请选择'}}
            </view>
          </picker>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
            {{sexIndex ? sexArray[sexIndex] : '暂无设置'}}
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">体重</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <input class="item-value" placeholder="请输入体重" type="digit" placeholder-style="color: #afafaf" v-model="weight"/>
          <span v-show="weight" class="unit-span">kg</span>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
            {{weight}}<span v-show="weight" class="unit-span">kg</span>
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">身高</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <input class="item-value" placeholder="请输入身高" type="digit" placeholder-style="color: #afafaf" v-model="height"/>
          <span v-show="height" class="unit-span">cm</span>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
            {{height}}<span v-show="height" class="unit-span">cm</span>
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">联系方式</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <input class="item-value" placeholder="请输入联系方式" type="number" placeholder-style="color: #afafaf" v-model="contact"/>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
            {{contact}}
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">就诊时间</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <picker mode="date" :value="visitDate" @change="bindDateChange">
            <view class="item-value">
              {{visitDate ? visitDate : '请选择'}}
            </view>
          </picker>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
            {{visitDate ? visitDate : '暂无设置'}}
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">有无过敏史</span>
        <div class="flex-row-v-center" v-if="isEdit">
          <picker @change="bindPickerChange('allergies', $event)" :value="allergies" :range="allergiesArray">
            <view class="item-value">
              {{allergiesIndex === '' ? '请选择' : allergiesArray[allergiesIndex]}}
            </view>
          </picker>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
             {{allergiesIndex === '' ? '暂无设置' : allergiesArray[allergiesIndex]}}
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="item-row flex-row-space-between flex-row-v-center">
        <span class="item-name">地址</span>
        <div class="flex-1 flex-row-v-center" v-if="isEdit">
          <input class="flex-1 item-value" placeholder="请输入地址" placeholder-style="color: #afafaf" v-model="address"/>
          <img class="item-arrow" src="/static/assets/img/icon_arrow.png"/>
        </div>
        <div class="flex-row-v-center" v-else>
          <span class="item-value">
             {{address}}
          </span>
        </div>
      </div>
      <div class="item-line"></div>
      <div class="medical-detail">
        <span>病情描述</span>
        <textarea v-if="isEdit"
                  placeholder="请输入您的病情"
                  auto-height="true"
                  v-model="desc"
                  placeholder-style="font-size: 14px;color: #afafaf;font-weight: 300;"/>
        <div style="font-size: 14px; margin-top: 16px; margin-left: 4px;" v-else>
          {{desc}}
        </div>
      </div>

      <div class="flex-center">
        <div class="btn-save" @click="onClickSave" v-if="isEdit">保存</div>
        <div class="btn-save" @click="onClickEdit" v-else>编辑</div>
        <div class="btn-del" @click="onClickDelete" v-if="id > 0 && from != 'dzbl'">删除</div>
      </div>
    </div>
  </div>
</template>

<script>
  import navbar from '@/components/navbar'
  import Core from 'core'
  import global from 'global'
  import Common from 'common'

  export default {
    components: {
      navbar
    },
    data () {
      return {
        id: 0,
        from: '',
        // todo  页面差很多 需要写
        statusH: global.state.statusH,
        titleH: global.state.titleH,
        imgs: [],

        ageArray: [],
        age: 23,
        ageIndex: '',

        sexArray: ['未知', '男', '女'],
        gender: '',
        sexIndex: '',

        allergiesArray: ['无', '有'],
        allergies: '',
        allergiesIndex: '',

        name: '',
        wxAccount: '',
        weight: '',
        height: '',
        contact: '',
        visitDate: '',
        address: '',
        desc: '',

        isEdit: false,
        title: ''
      }
    },

    onLoad () {
      this.initData()
      let arr = []
      for (let i = 1; i <= 100; i++) {
        arr.push(i)
      }
      this.ageArray = arr

      let user = Core.Data.getUser()

      this.name = user.nickname
      this.gender = user.gender || ''
      this.sexIndex = user.gender || ''
      this.contact = user.phone || ''
      this.address = `${user.province} ${user.city} ${user.county} ${user.address}` || ''

      if (user.birthday) {
        this.age = Core.Util.getDiffDate(user.birthday, Core.Util.getTodayBegin())
        this.ageIndex = this.age
      }
      // console.log("======>", this)
      let id = this.$root.$mp.query['id']
      let from = this.$root.$mp.query['from']
      this.id = id
      this.from = from || ''
      if (parseInt(id) > 0) {
        this.title = '创建病历'
        this.isEdit = false
        this._getHospitalCardDetail(id, (res) => {
          this.name = res.name
          this.wxAccount = res.wx_account;
          this.gender = res.gender || ''
          this.sexIndex = res.gender || ''
          this.contact = res.contact || ''
          this.address = res.address || ''

          this.age = Core.Util.getDiffDate(res.birthday, Core.Util.getTodayBegin())
          this.ageIndex = this.age
          this.desc = res.description
          this.allergies = res.anaphylaxis
          this.allergiesIndex = res.anaphylaxis
          this.weight = res.body_weight.substr(0, res.body_weight.length - 2)
          this.height = res.body_height.substr(0, res.body_height.length - 2)
          this.visitDate = Core.Util.timeFormat(res.visit_time, 'Y-m-d')
          this.imgs = res.img_list_arr
        })
      } else {
        this.title = '病历信息'
        this.isEdit = true
      }

      if (from === 'dzbl') {
        this.isEdit = true
      }
    },

    methods: {
      initData () {
        this.imgs = []
        this.ageArray = []
        this.age = 23
        this.ageIndex = ''
        this.gender = ''
        this.sexIndex = ''
        this.allergies = ''
        this.allergiesIndex = ''

        this.name = ''
        this.wxAccount = ''
        this.weight = ''
        this.height = ''
        this.contact = ''
        this.visitDate = ''
        this.address = ''
        this.desc = ''
      },

      onClickEdit () {
        this.isEdit = true;
      },

      onClickGoBack () {
        Core.Util.goBack()
      },

      onClickSave () {
        let name = this.name
        let wxAccount = this.wxAccount
        let birthday = Core.Util.dateAgo(this.age, 0, 0)
        let gender = this.gender
        let bodyWeight = this.weight
        let bodyHeight = this.height
        let contact = this.contact
        let visitTime = parseInt(new Date(this.visitDate).getTime() / 1000, 10)
        let allergies = this.allergies
        let address = this.address
        let desc = this.desc
        let imgList = this.imgs.join(',')

        if (!name) {
          this.showErrorMsg('请输入姓名')
          return
        }

        if (!wxAccount) {
          this.showErrorMsg("请输入微信号");
          return
        }

        // if (!bodyWeight) {
        //   this.showErrorMsg('请输入体重')
        //   return
        // }
        //
        // if (!bodyHeight) {
        //   this.showErrorMsg('请输入身高')
        //   return
        // }

        // if (!contact) {
        //   this.showErrorMsg('请输入联系方式')
        //   return
        // }
        if (contact && !Core.Util.isPhone(contact)) {
          this.showErrorMsg('请输入正确的手机号')
          return
        }



        if (!visitTime) {
          this.showErrorMsg('请选择就诊时间')
          return
        }

        // if (allergies === '') {
        //   this.showErrorMsg('请选择有无过敏史')
        //   return
        // }

        // if (!address) {
        //   this.showErrorMsg('请输入地址')
        //   return
        // }

        let id = (this.$root.$mp.query && this.$root.$mp.query['id']) || ''
        console.log('====>', id)
        this._saveHospitalCard(id, name, wxAccount, birthday, gender, bodyWeight + 'kg', bodyHeight + 'cm',
          contact, visitTime, allergies, address, desc, imgList, (res) => {
            Core.Event.emit('save_hospital_card', id)
            Core.Util.goBack()
          })
      },

      showErrorMsg (msg) {
        wx.showModal({
          title: '',
          content: msg,
          showCancel: false
        })
      },

      onClickDelete () {
        Core.Api.HospitalCard.deleteHospitalCard(this.id)
          .then(res => {
            Core.Event.emit('save_hospital_card', 0);
            Core.Util.goBack();
          })
          .catch(err => {
            Core.Util.showTip('', err.message)
          })
      },

      bindDateChange (e) {
        this.visitDate = e.mp.detail.value
      },

      bindPickerChange (t, e) {
        switch (t) {
          case 'age':
            this.age = e.mp.detail.value
            this.ageIndex = e.mp.detail.value
            break
          case 'sex':
            this.gender = e.mp.detail.value
            this.sexIndex = e.mp.detail.value
            break
          case 'allergies':
            this.allergies = e.mp.detail.value
            this.allergiesIndex = e.mp.detail.value
            break
          default:
            break
        }
      },

      handleUpload () {
        let $this = this
        wx.chooseImage({
          success: function (res) {
            let tempFilePaths = res.tempFilePaths
            console.log(tempFilePaths)
            tempFilePaths.forEach(v => {
              wx.showLoading({
                title: '图片上传中'
              })
              wx.uploadFile({
                url: Core.Const.NET.FILE_UPLOAD_END_POINT,
                filePath: v,
                name: 'file',
                success: function (res) {
                  wx.hideLoading()
                  if (res.statusCode == 200 && res.data) {
                    let parseData = JSON.parse(res.data)
                    $this.imgs.push(parseData.data.file_url)
                  }
                },
                fail (err) {
                  wx.hideLoading()
                  Core.Util.showTip('', err.errMsg)
                }
              })
            })
          },
          fail: function (err) {
            console.error('图片选择失败', err)
          }
        })
      },

      _getHospitalCardDetail (id, callback) {
        Core.Api.HospitalCard.getHospitalCardDetail(id)
          .then(res => {
            callback(res.hospital_card)
          })
          .catch(err => {
            Core.Util.showTip('', err.message)
          })
      },

      _saveHospitalCard (id, name, wxAccount, birthday, gender, bodyWeight, bodyHeight,
        contact, visitTime, anaphylaxis, address, description, imgList, callback) {
        Core.Api.HospitalCard.saveHospitalCard(id, name, wxAccount, birthday, gender, bodyWeight, bodyHeight,
          contact, visitTime, anaphylaxis, address, description, imgList)
          .then(res => {
            callback(res)
          })
          .catch(err => {
            Core.Util.showTip('', err.message)
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .medical-create-page {
    width: 100%;
    height: 100%;
    position: relative;
    background: #FFFFFF;

    .medical-create-container {
      width: 100%;

      .line {
        width: 100%;
        height: 10px;
        background: #F5F5F5;
      }

      .item-row {
        width: 100%;
        height: 55px;
        background: #FFFFFF;
        padding-left: 13px;
        padding-right: 17px;

        .item-name {
          font-size: 16px;
          color: #313131;
          width: 100px;
        }

        .item-value {
          color: #565656;
          font-size: 14px;
          text-align: right;
          min-width: 50px;
          line-height: 50px;
          .unit-span {
            padding-left: 4px;
            font-size: 14px;
            color: #565656;
          }
        }

        .item-arrow {
          width: 7px;
          height: 13px;
          margin-left: 11px;
        }
      }

      .item-line {
        width: calc(100% - 30px);
        margin-left: 13px;
        height: 1px;
        background: #F4F4F4;
      }

      .medical-detail {
        padding: 10px 0 10px 13px;
        width: 100%;
        background: #ffffff;

        span {
          color: #313131;
          font-size: 16px;
        }

        textarea {
          margin-top: 18px;
          padding-left: 7px;
          font-size: 14px;
          color: #313131;
        }

      }

      .pic-add {
        width: 100%;
        padding-left: 20px;
        margin-top: 40px;

        .img-list {
          img {
            margin-right: 10px;
          }
        }

        img {
          width: 74px;
          height: 74px;
        }

        span {
          margin-left: 5px;
          color: #939393;
          font-size: 12px;
        }
      }

      .btn-save {
        width: 119px;
        height: 37px;
        margin-top: 40px;
        margin-bottom: 37px;
        color: #FFFFFF;
        font-size: 16px;
        border-radius: 18px;
        text-align: center;
        line-height: 37px;
        background: #0EC5A9;
        margin-right: 20px;
      }
      .btn-del {
        width: 119px;
        height: 37px;
        margin-top: 40px;
        margin-bottom: 37px;
        color: #FFFFFF;
        font-size: 16px;
        font-weight: 300;
        border-radius: 18px;
        text-align: center;
        line-height: 37px;
        background: linear-gradient(to right, rgb(252, 79, 7), rgb(252, 57, 7));
      }
    }
  }
</style>
